<template>
  <div class="course-list">
    <div class="page-header">
      <h2>全部课程</h2>
      <el-button v-if="isAdmin" type="primary" @click="showAddDialog">
        <el-icon><Plus /></el-icon>添加课程
      </el-button>
    </div>

    <div class="container">
      <!-- 筛选栏 -->
      <div class="filter-bar card">
        <div class="filter-content">
          <el-input
            v-model="filters.keyword"
            placeholder="搜索课程名称、讲师、标签..."
            class="search-input"
            @keyup.enter="handleSearch"
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
          <el-select v-model="filters.level" placeholder="难度等级" class="filter-select" @change="handleSearch">
            <el-option label="全部" value="" />
            <el-option label="入门" value="beginner" />
            <el-option label="中级" value="intermediate" />
            <el-option label="高级" value="advanced" />
          </el-select>
          <el-select v-model="filters.sort" placeholder="排序方式" class="filter-select" @change="handleSearch">
            <el-option label="最新" value="newest" />
            <el-option label="最热" value="hottest" />
            <el-option label="评分最高" value="rating" />
          </el-select>
          <el-button type="primary" @click="resetFilters">重置筛选</el-button>
        </div>
      </div>

      <!-- 课程列表 -->
      <div class="course-grid">
        <el-row :gutter="20">
          <el-col :span="6" v-for="course in paginatedCourses" :key="course.id">
            <div class="course-card card">
              <div class="course-image" @click="goToCourse(course)">
                <img :src="course.img" :alt="course.title">
                <div class="course-tag" v-if="course.isNew">新课</div>
                <div class="course-level" :class="course.level">{{ course.levelText }}</div>
              </div>
              <div class="course-content">
                <h3 @click="goToCourse(course)">{{ course.title }}</h3>
                <p class="course-desc">{{ course.desc }}</p>
                <div class="course-info">
                  <span class="teacher">
                    <el-icon><User /></el-icon>
                    {{ course.teacher }}
                  </span>
                  <div class="course-meta">
                    <span class="students">
                      <el-icon><UserFilled /></el-icon>
                      {{ course.students }}人学习
                    </span>
                    <span class="rating">
                      <el-icon><Star /></el-icon>
                      {{ course.rating }}
                    </span>
                  </div>
                </div>
                <div class="course-footer">
                  <div class="tags">
                    <el-tag
                      v-for="tag in course.tags"
                      :key="tag"
                      size="small"
                      class="tag"
                    >
                      {{ tag }}
                    </el-tag>
                  </div>
                  <div class="price" v-if="course.price > 0">
                    ¥{{ course.price }}
                  </div>
                  <div class="price free" v-else>
                    免费
                  </div>
                </div>
                <div class="course-actions">
                  <el-button type="primary" @click="goToCourse(course)">查看详情</el-button>
                  <template v-if="isAdmin">
                    <el-button type="warning" @click.stop="handleEdit(course)">
                      <el-icon><Edit /></el-icon>
                    </el-button>
                    <el-button type="danger" @click.stop="handleDelete(course)">
                      <el-icon><Delete /></el-icon>
                    </el-button>
                  </template>
                </div>
              </div>
            </div>
          </el-col>
        </el-row>
      </div>

      <!-- 分页 -->
      <div class="pagination" v-if="filteredCourses.length > 0">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :total="total"
          :page-sizes="[8, 16, 24, 32]"
          layout="total, prev, pager, next"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>

      <!-- 无数据提示 -->
      <el-empty v-if="filteredCourses.length === 0" description="暂无符合条件的课程" />
    </div>

    <!-- 添加/编辑课程对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="isEdit ? '编辑课程' : '添加课程'"
      width="600px"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="课程名称" prop="title">
          <el-input v-model="form.title" placeholder="请输入课程名称" />
        </el-form-item>
        <el-form-item label="课程描述" prop="description">
          <el-input
            v-model="form.description"
            type="textarea"
            :rows="3"
            placeholder="请输入课程描述"
          />
        </el-form-item>
        <el-form-item label="讲师" prop="teacher">
          <el-input v-model="form.teacher" placeholder="请输入讲师姓名" />
        </el-form-item>
        <el-form-item label="难度等级" prop="level">
          <el-select v-model="form.level" placeholder="请选择难度等级">
            <el-option label="入门" value="beginner" />
            <el-option label="初级" value="intermediate" />
            <el-option label="中级" value="advanced" />
          </el-select>
        </el-form-item>
        <el-form-item label="价格" prop="price">
          <el-input-number
            v-model="form.price"
            :min="0"
            :precision="2"
            :step="10"
          />
        </el-form-item>
        <el-form-item label="封面图片" prop="image">
          <el-input v-model="form.image" placeholder="请输入图片URL" />
        </el-form-item>
        <el-form-item label="标签" prop="tags">
          <el-select
            v-model="form.tags"
            multiple
            filterable
            allow-create
            placeholder="请选择或输入标签"
          >
            <el-option
              v-for="tag in tagOptions"
              :key="tag"
              :label="tag"
              :value="tag"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="分类" prop="category">
          <el-select v-model="form.category" placeholder="请选择分类">
            <el-option
              v-for="category in categoryOptions"
              :key="category.value"
              :label="category.label"
              :value="category.value"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, watch, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { Search, User, UserFilled, Star, Plus, Edit, Delete } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useCourseStore } from '@/stores/course'

const router = useRouter()
const courseStore = useCourseStore()

// 筛选条件
const filters = reactive({
  level: '',
  sort: 'newest',
  keyword: '',
  category: ''
})

// 课程分类
const categories = [
  { label: '全部课程', value: '' }
]

// 分页
const currentPage = ref(1)
const pageSize = ref(8)
const total = computed(() => filteredCourses.value.length)

// 管理员状态
const isAdmin = computed(() => localStorage.getItem('role') === 'admin')

// 课程数据
const courses = ref([
  {
    id: 1,
    title: 'Vue3 实战教程',
    desc: '从入门到精通，掌握Vue3开发技能',
    teacher: '张老师',
    img: 'https://picsum.photos/400/300?random=1',
    students: 1234,
    rating: 4.9,
    isNew: true,
    level: 'beginner',
    levelText: '入门',
    price: 299,
    tags: ['Vue.js', '前端开发'],
    category: '前端开发'
  },
  {
    id: 2,
    title: 'React 18 新特性详解',
    desc: '深入学习React 18的新特性和最佳实践',
    teacher: '李老师',
    img: 'https://picsum.photos/400/300?random=2',
    students: 2345,
    rating: 4.8,
    isNew: true,
    level: 'intermediate',
    levelText: '中级',
    price: 399,
    tags: ['React', '前端开发'],
    category: '前端开发'
  },
  {
    id: 3,
    title: 'Node.js 企业级应用开发',
    desc: '从零开始构建企业级Node.js应用',
    teacher: '王老师',
    img: 'https://picsum.photos/400/300?random=3',
    students: 3456,
    rating: 4.7,
    level: 'advanced',
    levelText: '高级',
    price: 499,
    tags: ['Node.js', '后端开发'],
    category: '后端开发'
  },
  {
    id: 4,
    title: 'TypeScript 高级编程',
    desc: '掌握TypeScript高级特性和最佳实践',
    teacher: '赵老师',
    img: 'https://picsum.photos/400/300?random=4',
    students: 4567,
    rating: 4.8,
    level: 'intermediate',
    levelText: '中级',
    price: 399,
    tags: ['TypeScript', '前端开发'],
    category: '前端开发'
  },
  {
    id: 5,
    title: 'Python 数据分析实战',
    desc: '使用Python进行数据分析和可视化',
    teacher: '钱老师',
    img: 'https://picsum.photos/400/300?random=5',
    students: 5678,
    rating: 4.9,
    level: 'intermediate',
    levelText: '中级',
    price: 299,
    tags: ['Python', '数据分析'],
    category: '数据分析'
  },
  {
    id: 6,
    title: 'Docker 容器化部署',
    desc: '掌握Docker容器化部署技术',
    teacher: '孙老师',
    img: 'https://picsum.photos/400/300?random=6',
    students: 6789,
    rating: 4.7,
    level: 'advanced',
    levelText: '高级',
    price: 399,
    tags: ['Docker', '运维'],
    category: '运维'
  },
  {
    id: 7,
    title: 'Flutter 跨平台开发',
    desc: '使用Flutter开发跨平台应用',
    teacher: '周老师',
    img: 'https://picsum.photos/400/300?random=7',
    students: 7890,
    rating: 4.8,
    isNew: true,
    level: 'intermediate',
    levelText: '中级',
    price: 499,
    tags: ['Flutter', '移动开发'],
    category: '移动开发'
  },
  {
    id: 8,
    title: 'Spring Boot 微服务开发',
    desc: '使用Spring Boot构建微服务应用',
    teacher: '吴老师',
    img: 'https://picsum.photos/400/300?random=8',
    students: 8901,
    rating: 4.9,
    level: 'advanced',
    levelText: '高级',
    price: 599,
    tags: ['Spring Boot', '后端开发'],
    category: '后端开发'
  },
  {
    id: 9,
    title: 'UI/UX 设计基础',
    desc: '掌握UI/UX设计的基本原则和工具',
    teacher: '郑老师',
    img: 'https://picsum.photos/400/300?random=9',
    students: 9012,
    rating: 4.8,
    level: 'beginner',
    levelText: '入门',
    price: 299,
    tags: ['UI设计', 'UX设计'],
    category: 'UI设计'
  },
  {
    id: 10,
    title: '人工智能入门',
    desc: '人工智能基础知识和应用实践',
    teacher: '王老师',
    img: 'https://picsum.photos/400/300?random=10',
    students: 3456,
    rating: 4.7,
    level: 'beginner',
    levelText: '入门',
    price: 399,
    tags: ['人工智能', '机器学习'],
    category: '人工智能'
  },
  {
    id: 11,
    title: 'Web安全实战',
    desc: 'Web安全攻防实战演练',
    teacher: '李老师',
    img: 'https://picsum.photos/400/300?random=11',
    students: 2345,
    rating: 4.8,
    level: 'advanced',
    levelText: '高级',
    price: 499,
    tags: ['网络安全', 'Web安全'],
    category: '后端开发'
  },
  {
    id: 12,
    title: 'Git 版本控制',
    desc: 'Git版本控制工具使用指南',
    teacher: '张老师',
    img: 'https://picsum.photos/400/300?random=12',
    students: 1234,
    rating: 4.9,
    level: 'beginner',
    levelText: '入门',
    price: 0,
    tags: ['Git', '开发工具'],
    category: '后端开发'
  }
])

// 过滤后的课程列表
const filteredCourses = computed(() => {
  let result = [...courses.value]
  
  // 关键词搜索
  if (filters.keyword) {
    const keyword = filters.keyword.toLowerCase()
    result = result.filter(course => 
      course.title.toLowerCase().includes(keyword) || 
      course.desc.toLowerCase().includes(keyword) ||
      course.teacher.toLowerCase().includes(keyword) ||
      course.tags.some(tag => tag.toLowerCase().includes(keyword))
    )
  }
  
  // 难度等级筛选
  if (filters.level) {
    result = result.filter(course => course.level === filters.level)
  }

  // 分类筛选
  if (filters.category) {
    result = result.filter(course => course.category === filters.category)
  }
  
  // 排序
  switch (filters.sort) {
    case 'newest':
      result.sort((a, b) => b.id - a.id)
      break
    case 'hottest':
      result.sort((a, b) => b.students - a.students)
      break
    case 'rating':
      result.sort((a, b) => b.rating - a.rating)
      break
  }
  
  return result
})

// 分页后的课程列表
const paginatedCourses = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return filteredCourses.value.slice(start, end)
})

// 处理搜索
function handleSearch() {
  currentPage.value = 1
}

// 重置筛选条件
function resetFilters() {
  filters.keyword = ''
  filters.level = ''
  filters.category = ''
  filters.sort = 'newest'
  currentPage.value = 1
  handleSearch()
}

// 监听筛选条件变化
watch([() => filters.keyword, () => filters.level, () => filters.sort, () => filters.category], () => {
  handleSearch()
})

// 处理分页
function handleSizeChange(val) {
  pageSize.value = val
  currentPage.value = 1
}

function handleCurrentChange(val) {
  currentPage.value = val
}

// 跳转到课程详情
function goToCourse(course) {
  router.push({
    path: `/course/${course.id}`,
    query: {
      title: course.title,
      content: course.desc,
      teacher: course.teacher,
      img: course.img,
      students: course.students,
      rating: course.rating
    }
  })
}

// 对话框相关
const dialogVisible = ref(false)
const isEdit = ref(false)
const formRef = ref(null)
const form = ref({
  title: '',
  description: '',
  teacher: '',
  level: '',
  price: 0,
  image: '',
  tags: [],
  category: '',
  students: 0,
  rating: 5,
  isNew: true
})

// 标签选项
const tagOptions = ['前端', '后端', '移动端', '数据库', '人工智能', '云计算']

// 分类选项
const categoryOptions = [
  { label: '编程开发', value: 'programming' },
  { label: '人工智能', value: 'ai' },
  { label: '数据科学', value: 'data' },
  { label: '云计算', value: 'cloud' },
  { label: '运维测试', value: 'ops' },
  { label: 'UI设计', value: 'design' },
  { label: '产品经理', value: 'pm' }
]

// 表单验证规则
const rules = {
  title: [
    { required: true, message: '请输入课程名称', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  description: [
    { required: true, message: '请输入课程描述', trigger: 'blur' }
  ],
  teacher: [
    { required: true, message: '请输入讲师姓名', trigger: 'blur' }
  ],
  level: [
    { required: true, message: '请选择难度等级', trigger: 'change' }
  ],
  price: [
    { required: true, message: '请输入价格', trigger: 'blur' }
  ],
  image: [
    { required: true, message: '请输入封面图片URL', trigger: 'blur' }
  ],
  tags: [
    { required: true, message: '请选择标签', trigger: 'change' }
  ],
  category: [
    { required: true, message: '请选择分类', trigger: 'change' }
  ]
}

// 处理编辑
function handleEdit(course) {
  isEdit.value = true
  form.value = {
    id: course.id,
    title: course.title,
    description: course.desc,
    teacher: course.teacher,
    level: course.level,
    price: course.price,
    image: course.img,
    tags: course.tags,
    category: course.category,
    students: course.students,
    rating: course.rating,
    isNew: course.isNew
  }
  dialogVisible.value = true
}

// 处理删除
function handleDelete(course) {
  ElMessageBox.confirm(
    '确定要删除该课程吗？',
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    const index = courses.value.findIndex(c => c.id === course.id)
    if (index !== -1) {
      courses.value.splice(index, 1)
      // 保存到 localStorage
      localStorage.setItem('courses', JSON.stringify(courses.value))
      ElMessage.success('删除成功')
    }
  }).catch(() => {})
}

// 处理提交
async function handleSubmit() {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    
    const courseData = {
      id: isEdit.value ? form.value.id : Date.now(),
      title: form.value.title,
      desc: form.value.description,
      teacher: form.value.teacher,
      level: form.value.level,
      levelText: getLevelText(form.value.level),
      price: form.value.price,
      img: form.value.image,
      tags: form.value.tags,
      category: form.value.category,
      students: isEdit.value ? form.value.students : 0,
      rating: isEdit.value ? form.value.rating : 5,
      isNew: isEdit.value ? form.value.isNew : true
    }
    
    if (isEdit.value) {
      const index = courses.value.findIndex(c => c.id === courseData.id)
      if (index !== -1) {
        courses.value[index] = courseData
      }
    } else {
      courses.value.unshift(courseData)
    }
    
    // 保存到 localStorage
    localStorage.setItem('courses', JSON.stringify(courses.value))
    
    ElMessage.success(isEdit.value ? '更新成功' : '添加成功')
    dialogVisible.value = false
  } catch (error) {
    ElMessage.error('请检查表单信息')
  }
}

// 获取难度等级文本
function getLevelText(level) {
  const levelMap = {
    'beginner': '入门',
    'intermediate': '中级',
    'advanced': '高级'
  }
  return levelMap[level] || '入门'
}

// 显示添加对话框
function showAddDialog() {
  isEdit.value = false
  form.value = {
    title: '',
    description: '',
    teacher: '',
    level: '',
    price: 0,
    image: '',
    tags: [],
    category: '',
    students: 0,
    rating: 5,
    isNew: true
  }
  dialogVisible.value = true
}

// 初始化时从 localStorage 加载数据
function loadCoursesFromStorage() {
  const storedCourses = localStorage.getItem('courses')
  if (storedCourses) {
    courses.value = JSON.parse(storedCourses)
  } else {
    // 如果没有存储的数据，使用默认数据
    courses.value = [
      {
        id: 1,
        title: 'Vue3 实战教程',
        desc: '从入门到精通，掌握Vue3开发技能',
        teacher: '张老师',
        img: 'https://picsum.photos/400/300?random=1',
        students: 1234,
        rating: 4.9,
        isNew: true,
        level: 'beginner',
        levelText: '入门',
        price: 299,
        tags: ['Vue.js', '前端开发'],
        category: '前端开发'
      },
      // ... 其他默认课程数据 ...
    ]
    // 保存默认数据到 localStorage
    localStorage.setItem('courses', JSON.stringify(courses.value))
  }
}

// 在组件挂载时加载数据
onMounted(() => {
  loadCoursesFromStorage()
})
</script>

<style scoped>
.course-list {
  padding: 20px;
  background-color: var(--bg-color);
  min-height: 100vh;
}

.container {
  max-width: 1200px;
  margin: 0 auto;
}

.filter-bar {
  margin-bottom: 20px;
  padding: 20px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.filter-content {
  display: flex;
  gap: 16px;
  align-items: center;
  flex-wrap: wrap;
}

.search-input {
  flex: 1;
  min-width: 300px;
}

.filter-select {
  width: 140px;
}

.el-button {
  margin-left: 8px;
}

.course-grid {
  margin-bottom: 20px;
}

.course-card {
  margin-bottom: 20px;
  background-color: #fff;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.course-image {
  position: relative;
  height: 200px;
  overflow: hidden;
  cursor: pointer;
}

.course-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  transition: transform 0.3s ease;
}

.course-card:hover .course-image img {
  transform: scale(1.05);
}

.course-tag {
  position: absolute;
  top: 12px;
  right: 12px;
  background: #f56c6c;
  color: white;
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
}

.course-level {
  position: absolute;
  top: 12px;
  left: 12px;
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
  color: white;
}

.course-level.beginner {
  background: #67c23a;
}

.course-level.intermediate {
  background: #e6a23c;
}

.course-level.advanced {
  background: #f56c6c;
}

.course-content {
  padding: 20px;
}

.course-content h3 {
  margin: 0 0 8px;
  font-size: 18px;
  color: var(--text-primary);
  cursor: pointer;
}

.course-content h3:hover {
  color: var(--primary-color);
}

.course-desc {
  margin: 0 0 12px;
  color: var(--text-secondary);
  font-size: 14px;
  line-height: 1.5;
  height: 42px;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
}

.course-info {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
}

.course-meta {
  display: flex;
  gap: 12px;
  color: var(--text-light);
  font-size: 14px;
}

.course-meta span {
  display: flex;
  align-items: center;
  gap: 4px;
}

.course-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.tags {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
}

.tag {
  margin-right: 4px;
}

.price {
  color: #f56c6c;
  font-size: 18px;
  font-weight: bold;
}

.price.free {
  color: #67c23a;
}

.pagination {
  display: flex;
  justify-content: center;
  margin-top: 20px;
  padding: 20px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

.course-actions {
  display: flex;
  gap: 8px;
  margin-top: 12px;
}

.course-actions .el-button {
  flex: 1;
}
</style> 